package cn.oesoft.blog.web.client;

import cn.oesoft.blog.model.domain.User;
import cn.oesoft.blog.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author ：zhaoweiwei
 * @date ：创建于 2025/5/15 15:14
 * @description：
 * @modified By：
 * @version: 1.0.0
 */
@Controller
public class RegistController {
    private static final Logger logger = LoggerFactory.getLogger(RegistController.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 向注册页面跳转
    @GetMapping(value = "/regist")
    public String toRegist() {
        return "comm/regist";
    }

    // 注册
    @PostMapping(value = "/regist")
    public String regist(HttpServletRequest request,
                         @RequestParam String username, @RequestParam String password, @RequestParam String email) {

        // 封装用户信息
        password=passwordEncoder.encode(password);
        User user= new User(username,password,email);
        user.setCreated(new Date());
        user.setValid(1);
        try {
            userService.addUser(user);
            logger.info("新增用户成功，对应用户id: "+user.getId());
            return "redirect:/";
        } catch (Exception e) {
            logger.error("新增用户失败"+"错误描述: "+e.getMessage());
            return "redirect:/regist?error";
        }
    }
}
